//
//  LoginViewController.m
//  jingjing2.0
//
//  Created by apple on 16/4/28.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "LoginViewController.h"
#import "Header.h"
@interface LoginViewController ()
@property(nonatomic,strong)NSDate *sendTime;
@property(nonatomic,strong)NSTimer *timer;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark--获取验证码
- (IBAction)getCodeClick:(id)sender {
    if (self.phoneNumber.text.length==0)
    {
        [MBProgressHUD showError:@"手机号不能为空"];
        [self.phoneNumber becomeFirstResponder];
    }else if ([GeneralTool valiMobile:self.phoneNumber.text]!=nil)
    {
        [MBProgressHUD showError:[GeneralTool valiMobile:self.phoneNumber.text]];
        //不符合格式的手机号先清空
        self.phoneNumber.text=@"";
        //将光标移到输入手机号
        [self.phoneNumber becomeFirstResponder];
    }else
    {
        
        [MBProgressHUD showMessage:@"正在发送" toView:self.view];
        //获取时间戳
        NSString *timestamp = [GeneralTool gettimestamp];
        //拼接请求参数
        NSDictionary *signDic=[[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects:self.phoneNumber.text,timestamp,nil] forKeys:[NSArray arrayWithObjects:@"Mobile",@"Timestamp",nil]];
        //获取加密后的请求参数
        NSString* sign=[GeneralTool GetSin:signDic];
        //请求数据
        NSDictionary *dict=@{
                             @"Mobile":self.phoneNumber.text,
                             @"Timestamp":timestamp,
                             @"Sign":sign
                             };
        NSDictionary *parameters=@{@"m_LoginReCode":dict};
        

        //发送请求
        [RequestTool requestDataWithType:@"post" andUrlString:@"User/LoginReCode" andParameters:parameters andRequestFinished:^(id responses, NSError *error)
        {
        
            [MBProgressHUD hideHUDForView:self.view];
            NSString *str =[responses[@"ReturnString"]stringByRemovingPercentEncoding];
            NSLog(@"str=%@",str);
            if ([str isEqualToString:@"发送成功"])
            {
              //记录发送的时间
                _sendTime=[NSDate date];
                
                [MBProgressHUD showSuccess:@"发送成功，请输入收到的短信验证码"];
                
                //改变光标位置
                [self.messageCheck becomeFirstResponder];
                
                //开启定时器
                if (!_timer)
                {
                    _timer=[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(countRemainingTime) userInfo:nil repeats:YES];
                    [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
                }else
                {
                    [_timer setFireDate:[NSDate date]];
                }
  
            }else
            {
                if(!IsNilString(str))
                {
                  [MBProgressHUD showError:str];
                }
            }
            }];
        
        }
}

//定时器绑定方法
-(void)countRemainingTime
{
    //获取当前时间
    NSDate *currentDate=[NSDate date];
    //每秒钟计算当前时间与发送时间的差来进行倒计时
    NSTimeInterval timerInternal=[currentDate timeIntervalSinceDate:_sendTime];
    [self.getCode setTitle:[NSString stringWithFormat:@"%d秒",60-(int)timerInternal] forState:UIControlStateNormal];
    
    //时间超时
    if (timerInternal >= 60) {
        [_timer setFireDate:[NSDate distantFuture]];
        [self.getCode setTitle:@"重新发送" forState:UIControlStateNormal];
    }
    
}
#pragma mark--确认登录
- (IBAction)sureLoginClick:(id)sender {
    if (self.phoneNumber.text.length==0) {
        [MBProgressHUD showError:@"手机号不能为空"];
    }
    else if ([GeneralTool valiMobile:self.phoneNumber.text]!=nil)
    {
       [MBProgressHUD showError:[GeneralTool valiMobile:self.phoneNumber.text]];
    }else if (self.messageCheck.text.length==0) {
        [MBProgressHUD showError:@"验证码不能为空"];
    }else
    {
        if (GETCITYCODE) {
            NSString *timeStamp=[GeneralTool gettimestamp];
            
            NSDictionary *signDic=@{@"Mobile":self.phoneNumber.text,
                                    @"Code":self.messageCheck.text,
                                    @"ClientType":CLIENTTYPE,
                                    @"CityCode":GETCITYCODE,
                                    @"Timestamp":timeStamp};
            NSString *sign=[GeneralTool GetSin:signDic];
            NSDictionary *dic=@{@"Mobile":self.phoneNumber.text,
                                @"Code":self.messageCheck.text,
                                @"ClientType":CLIENTTYPE,
                                @"CityCode":GETCITYCODE,
                                @"Timestamp":timeStamp,
                                @"Sign":sign};
            NSDictionary *requeatDic=@{@"m_LoginCheckCode":dic};
            [RequestTool requestDataWithType:@"post" andUrlString:@"User/LoginCheckCode" andParameters:requeatDic andRequestFinished:^(id responses, NSError *error) {
                NSString *returnString=[responses[@"ReturnString"]stringByRemovingPercentEncoding];
                if (error) {
                    [MBProgressHUD showError:@"登录失败，请稍后尝试"];
                }else if ([returnString isEqualToString:@"登录成功"])
                {
                    NSDictionary *returnObject=responses[@"ReturnObject"];
                    NSString *userCode=returnObject[@"UserCode"];
                    NSUserDefaults *data=[NSUserDefaults standardUserDefaults];
                    [data setObject:userCode forKey:@"UserCode"];
                    [data synchronize];
                    
                }else
                {
                    [MBProgressHUD showError:returnString];
                }
            }];

        }
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
@end
